'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import type { Trip, Activity } from '@prisma/client';
import { format } from 'date-fns';

type TripWithActivities = Trip & {
  activities: Activity[];
};

interface TripFormProps {
  initialData?: TripWithActivities;
}

// 修改输入框的基础样式类
const inputBaseClass = `mt-1 block w-full rounded-md bg-white border-gray-300 
  text-gray-900 placeholder-gray-400 focus:border-blue-500 focus:ring-blue-500 
  shadow-sm font-medium px-4 py-2`;

const textareaBaseClass = `mt-1 block w-full rounded-md bg-white border-gray-300 
  text-gray-900 placeholder-gray-400 focus:border-blue-500 focus:ring-blue-500 
  shadow-sm px-4 py-2`;

// 活动输入框的样式类
const activityInputClass = `mt-1 block w-full rounded-md bg-white border-gray-300 
  text-gray-900 placeholder-gray-400 focus:border-blue-500 focus:ring-blue-500 
  shadow-sm font-medium px-4 py-2`;

const activityTextareaClass = `mt-1 block w-full rounded-md bg-white border-gray-300 
  text-gray-900 placeholder-gray-400 focus:border-blue-500 focus:ring-blue-500 
  shadow-sm px-4 py-2`;

export function TripForm({ initialData }: TripFormProps) {
  const router = useRouter();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [formData, setFormData] = useState({
    title: initialData?.title || '',
    description: initialData?.description || '',
    startDate: initialData?.startDate ? format(new Date(initialData.startDate), 'yyyy-MM-dd') : '',
    endDate: initialData?.endDate ? format(new Date(initialData.endDate), 'yyyy-MM-dd') : '',
    isPublic: initialData?.isPublic || false,
    activities: initialData?.activities.map(activity => ({
      id: activity.id,
      title: activity.title,
      description: activity.description || '',
      date: format(new Date(activity.date), 'yyyy-MM-dd'),
    })) || [{ id: '', title: '', description: '', date: '' }],
  });

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    setError(null);

    try {
      const response = await fetch(
        initialData ? `/api/trips/${initialData.id}` : '/api/trips',
        {
          method: initialData ? 'PUT' : 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(formData),
        }
      );

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || '保存失败');
      }

      // 跳转到行程列表页面并强制刷新
      router.push('/trips');
      router.refresh();
    } catch (error) {
      console.error('Submit error:', error);
      setError(error instanceof Error ? error.message : '保存失败');
      setIsSubmitting(false);
    }
  };

  const addActivity = () => {
    setFormData(prev => ({
      ...prev,
      activities: [
        ...prev.activities,
        { id: '', title: '', description: '', date: '' },
      ],
    }));
  };

  const removeActivity = (index: number) => {
    setFormData(prev => ({
      ...prev,
      activities: prev.activities.filter((_, i) => i !== index),
    }));
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      <div className="bg-white rounded-lg shadow-lg p-6 border border-gray-200">
        <div className="space-y-4">
          <div>
            <label htmlFor="title" className="block text-sm font-medium text-gray-700">
              行程标题
            </label>
            <input
              type="text"
              id="title"
              value={formData.title}
              onChange={e => setFormData(prev => ({ ...prev, title: e.target.value }))}
              className={inputBaseClass}
              placeholder="例如：北京3日游"
              required
            />
          </div>

          <div>
            <label htmlFor="description" className="block text-sm font-medium text-gray-700">
              行程描述
            </label>
            <textarea
              id="description"
              value={formData.description}
              onChange={e => setFormData(prev => ({ ...prev, description: e.target.value }))}
              className={textareaBaseClass}
              rows={3}
              placeholder="描述一下这次行程的亮点..."
            />
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label htmlFor="startDate" className="block text-sm font-medium text-gray-700">
                开始日期
              </label>
              <input
                type="date"
                id="startDate"
                value={formData.startDate}
                onChange={e => setFormData(prev => ({ ...prev, startDate: e.target.value }))}
                className={inputBaseClass}
                required
              />
            </div>

            <div>
              <label htmlFor="endDate" className="block text-sm font-medium text-gray-700">
                结束日期
              </label>
              <input
                type="date"
                id="endDate"
                value={formData.endDate}
                onChange={e => setFormData(prev => ({ ...prev, endDate: e.target.value }))}
                className={inputBaseClass}
                required
              />
            </div>
          </div>

          <div className="flex items-center space-x-2">
            <input
              type="checkbox"
              id="isPublic"
              checked={formData.isPublic}
              onChange={e => setFormData(prev => ({ ...prev, isPublic: e.target.checked }))}
              className="rounded bg-gray-700 border-gray-600 text-blue-500 
                focus:ring-blue-500 focus:ring-offset-gray-800"
            />
            <label htmlFor="isPublic" className="text-sm text-gray-700">
              公开行程（其他用户可以查看和收藏）
            </label>
          </div>
        </div>
      </div>

      <div className="bg-white rounded-lg shadow-lg p-6 border border-gray-200">
        <div className="flex justify-between items-center mb-4">
          <h2 className="text-xl font-bold text-gray-900">活动安排</h2>
          <span className="text-sm text-gray-500">
            已添加 {formData.activities.length} 个活动
          </span>
        </div>
        <div className="space-y-4">
          {formData.activities.map((activity, index) => (
            <div key={index} className="bg-gray-50 rounded-lg p-4 border border-gray-200">
              <div className="flex justify-between items-center mb-4">
                <h3 className="text-lg font-medium text-gray-900 flex items-center">
                  <span className="w-8 h-8 rounded-full bg-blue-600 text-white flex items-center justify-center mr-2 text-sm">
                    {index + 1}
                  </span>
                  活动 {index + 1}
                </h3>
                {formData.activities.length > 1 && (
                  <button
                    type="button"
                    onClick={() => removeActivity(index)}
                    className="text-red-400 hover:text-red-300 transition-colors flex items-center"
                  >
                    <svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                    </svg>
                    删除
                  </button>
                )}
              </div>

              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    活动标题
                  </label>
                  <input
                    type="text"
                    value={activity.title}
                    onChange={e => {
                      const newActivities = [...formData.activities];
                      newActivities[index].title = e.target.value;
                      setFormData(prev => ({ ...prev, activities: newActivities }));
                    }}
                    className={activityInputClass}
                    placeholder="例如：参观故宫"
                    required
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    活动描述
                  </label>
                  <textarea
                    value={activity.description}
                    onChange={e => {
                      const newActivities = [...formData.activities];
                      newActivities[index].description = e.target.value;
                      setFormData(prev => ({ ...prev, activities: newActivities }));
                    }}
                    className={activityTextareaClass}
                    rows={2}
                    placeholder="描述一下这个活动的具体安排..."
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    活动日期
                  </label>
                  <input
                    type="date"
                    value={activity.date}
                    onChange={e => {
                      const newActivities = [...formData.activities];
                      newActivities[index].date = e.target.value;
                      setFormData(prev => ({ ...prev, activities: newActivities }));
                    }}
                    className={activityInputClass}
                    required
                  />
                </div>
              </div>
            </div>
          ))}

          <button
            type="button"
            onClick={addActivity}
            className="w-full py-3 bg-gray-50 text-blue-600 rounded-md hover:bg-gray-100 
              transition-colors border border-gray-200 flex items-center justify-center"
          >
            <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
            添加新活动
          </button>
        </div>
      </div>

      {error && (
        <div className="text-red-500 text-sm mt-2">
          {error}
        </div>
      )}

      <div className="flex justify-end space-x-4">
        <button
          type="button"
          onClick={() => router.back()}
          className="px-6 py-2 bg-white text-gray-700 rounded-md hover:bg-gray-50 
            transition-colors border border-gray-300"
          disabled={isSubmitting}
        >
          取消
        </button>
        <button
          type="submit"
          disabled={isSubmitting}
          className="px-6 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 
            transition-colors disabled:opacity-50 disabled:cursor-not-allowed
            flex items-center"
        >
          {isSubmitting ? (
            <>
              <svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-white" fill="none" viewBox="0 0 24 24">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
              </svg>
              保存中...
            </>
          ) : '保存行程'}
        </button>
      </div>
    </form>
  );
} 